/** GetDateTime.cpp
 *
 * 获取DS1302芯片时间通过串口打印
 * 基于Ds1302 1.0.4版本修改及汉化 * 
 *
 * @license GNU Affero General Public License v3.0
 * @原Ds1302库开源地址 https://github.com/Treboada/Ds1302
 *@小小牛牛
 */
#include <Arduino.h>
#include <DS1302.h>

#define PIN_ENA  9      //定义芯片引脚  RST
#define PIN_CLK  11     //定义芯片引脚  CLK
#define PIN_DAT  10     //定义芯片引脚  DAT

// 创建一个DS1302实例
Ds1302 rtc(PIN_ENA, PIN_CLK, PIN_DAT);


const static char* WeekDays[] =
{
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
};


void setup()
{
    Serial.begin(9600);

    // 初始化 RTC  时钟芯片
    rtc.init();  

    // 检测时钟是否停止，若停止则设置初始时间
    if (rtc.isHalted())
    {
        Serial.println("RTC is halted. Setting time...");

        Ds1302::DateTime dt = {
            .year = 23,
            .month = Ds1302::MONTH_OCT,
            .day = 3,
            .hour = 11,
            .minute = 59,
            .second = 56,
            .dow = Ds1302::DOW_TUE
        };

        rtc.setDateTime(&dt);    //写入以上设置的初始时间数据到RTC芯片
    }
}


void loop()
{
    // 获取当前时间
    Ds1302::DateTime now;
    rtc.getDateTime(&now);

    static uint8_t last_second = 0;
    if (last_second != now.second)   //当读取到的秒数和上一次不一样时，刷新串口输出信息
    {
        last_second = now.second;

        Serial.print("20");
        Serial.print(now.year);    // 00-99
        Serial.print('-');
        if (now.month < 10) Serial.print('0');
        Serial.print(now.month);   // 01-12
        Serial.print('-');
        if (now.day < 10) Serial.print('0');
        Serial.print(now.day);     // 01-31
        Serial.print(' ');
        Serial.print(WeekDays[now.dow - 1]); // 1-7
       // Serial.print(now.dow); // 1-7
        Serial.print(' ');
        if (now.hour < 10) Serial.print('0');
        Serial.print(now.hour);    // 00-23
        Serial.print(':');
        if (now.minute < 10) Serial.print('0');
        Serial.print(now.minute);  // 00-59
        Serial.print(':');
        if (now.second < 10) Serial.print('0');
        Serial.print(now.second);  // 00-59
        Serial.println();
    }

    delay(100);
}
